import random
from faker import Faker
from sqlalchemy.exc import IntegrityError
from app import create_app


from app.ext import db
from app.models import User,Role,Admin,Comment,Tag,Movie,MovieCollect


import uuid


faker = Faker('zh_CN')


def fake_user(count=10):
    for v in range(count):
        user=User()
        user.name='windstarry'+str(v)
        user.pwd='123456'
        user.email=faker.email()
        user.phone=faker.phone_number()
        user.info=faker.sentence()
        user.face='avatar/'+str(v)+'.jpg'
        user.uuid=str(uuid.uuid4().hex)
        db.session.add(user)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()


def fake_tag():
    tag_list = ['科幻','战争','爱情','恐怖','玄幻','推理','动画','魔幻','喜剧','音乐','灾难','剧情','纪实']
    for i in range(len(tag_list)):
        tag = Tag(name=tag_list[i])
        db.session.add(tag)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()


def fake_movie():
    movie_list = ['环太平洋','飘','杀手27','变形金刚']
    for i in range(len(movie_list)):
        movie=Movie()
        movie.title = movie_list[i]
        movie.url = faker.url()
        movie.info = faker.sentence(nb_words=9, variable_nb_words=True, ext_word_list=None)
        movie.star = random.randint(1, 5)
        movie.logo = faker.url()
        movie.play_num = 0
        movie.comment_num = 0
        movie.area = faker.country()
        movie.release_time = faker.date_time()
        movie.length = random.randint(100, 160)
        movie.tag_id = random.randint(1, Tag.query.count())
        db.session.add(movie)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()


def fake_comment(count=20):
    #增加评论
    for i in range(count):
        comment = Comment()
        comment.content = faker.sentence(nb_words=4, variable_nb_words=True, ext_word_list=None)
        comment.movie_id = random.randint(1, Movie.query.count())
        comment.user_id = random.randint(1, User.query.count())
        db.session.add(comment)
        try:
            db.session.commit()
        except IntegrityError:
            db.session.rollback()

 
app = create_app()


with app.app_context():
    db.drop_all()
    db.create_all()    
    #添加角色
    role_exists=Role.query.filter_by(name='超级管理员').first()
    if not role_exists:
        role = Role(
                    name="超级管理员",
                    auths="",
                )
        db.session.add(role)
        db.session.commit()       
    # 创建一个超级管理员
    admin_exists=Admin.query.filter_by(name='admin').first()
    if not admin_exists:
        admin = Admin()
        admin.name='admin'
        admin.pwd = '123456'
        admin.is_super=0
        admin.role_id=1
        db.session.add(admin)
        db.session.commit()      
    fake_user(count=10)
    fake_tag()
    fake_movie()
    fake_comment(count=20)